package com.hp.bon.sgw.wh.mml.handler;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hp.bon.sgw.wh.mml.common.MMLSessionEntity;
import com.hp.bon.sgw.wh.mml.repositories.HttpResponseRepository;
import com.hp.bon.sgw.wh.mml.repositories.PropertyRepository;
import com.hp.bon.sgw.wh.mml.repositories.VCMsgRelayRepository;

public class HttpTimeoutHandler extends Thread {

	private static final Logger logger = LoggerFactory.getLogger(HttpTimeoutHandler.class);
	
	private boolean stop = false;
	
	private static HttpTimeoutHandler handler = null;
	
	public static void startHandler(){
		if(handler==null){
			handler = new HttpTimeoutHandler();			
		}
		handler.stop = false;
		handler.start();
	}
	
	public static void stopHandler(){
		handler.stop = true;
	}
	
	public static boolean isRunningHandler(){
		return handler.isAlive();
	}
	
	private HttpTimeoutHandler(){
		setDaemon(false);
	}
	
	@Override
	public void run() {
		logger.info("HttpTimeoutHandler is running...");
		while (true) {
			if(stop){
				break;
			}
			long timeout = PropertyRepository.getMsgTimeout();
			List<String> sidofTimeout = VCMsgRelayRepository.removeTimeoutSessionIds(timeout);
			for(String sessionId : sidofTimeout){
				MMLSessionEntity sessionEntity = VCMsgRelayRepository.remove(sessionId);
				sessionEntity.setTimeout(true);
				HttpResponseRepository.offer(sessionEntity);
			}
			if(sidofTimeout.isEmpty()){
				long sleepTime = PropertyRepository.getMsgTimeout();
				try {
					sleep(sleepTime);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} else {
				logger.warn("VCMsgRelayRepository: timeout msg num: " + sidofTimeout.size());
				logger.warn("VCMsgRelayRepository: timeout msg sid: " + sidofTimeout);
			}
		}
		logger.info("HttpTimeoutHandler is stop...");
	}
}
